package com.client;

import com.Async.RpcFuture;
import com.serializetool.Request;
import com.serializetool.Response;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class ClientHandler extends ChannelInboundHandlerAdapter {

//    static AtomicInteger time = new AtomicInteger(0);

    ClientBuilder clientBuilder;

    public ClientHandler(){
    }

    public ClientHandler(ClientBuilder clientBuilder){
        this.clientBuilder = clientBuilder;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception{
        Response response = (Response)msg;
        RpcFuture rpcFuture = clientBuilder.getResponseListener().get(response.getTaskId());
        if(rpcFuture!=null){
            if(!rpcFuture.cancelled()){
                if(response.getErrorMsg()!=null){
                    Request request = clientBuilder.getRequestStorage().get(response.getTaskId());
                    if(response.getErrorMsg().getCause().getClass()!=IllegalArgumentException.class&&rpcFuture.getRetryTime()<3){
                        ctx.channel().writeAndFlush(request);
                        rpcFuture.setRetryTime(rpcFuture.getRetryTime()+1);
                        return;
                    }
                    ClientTerminal.getClientTerminal().register.deleteService(rpcFuture.getServiceName(),rpcFuture.getSocket());
                    clientBuilder.getChannelMap().remove(ctx.channel());
                    if(ctx.channel().isActive()) ctx.channel().close();
                    rpcFuture.setError(response.getErrorMsg());
                }else{
                    rpcFuture.setSuccess(true);
                    rpcFuture.setResult(response.getResult());
                }
                rpcFuture.tryRunCallBack();
//                System.out.println(time.incrementAndGet());
//                System.out.println("临时观察结果为"+response);
            }
//          connection.close();
//          connection.notifyAll(msg);
            clientBuilder.getResponseListener().remove(response.getTaskId());
            clientBuilder.getRequestStorage().remove(response.getTaskId());
        }

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx,Throwable ex){

    }
}
